#include "label.h"
#include "paintdevice.h"

static RegisterElementType r("Label", Label());

Label::Label()
    :Element()
{
    setHeight(1);   // Defualt Height 1
}

bool Label::copyFrom(const Element *e)
{
    const Label *l = qobject_cast<const Label*>(e);
    if(!l) return false;

    this->text_binding_ = l->text_binding_;
    return Element::copyFrom(l);
}

Element *Label::clone() const
{
    Element *l = new Label();
    if(!l->copyFrom(this)){
        delete l;
        l = NULL;
    }

    return l;
}

QRect Label::sizeHint() const
{
    if(rect_.isValid())
        return rect_;

    return QRect(rect_.x(), rect_.y(), text().length(), 1);
}

void Label::adjustSize()
{
    int w = 0;
    for(QChar ch:text()){
        if(ch.unicode()>127){
            w += 2;
        }else{
            w ++;
        }
    }
    if(w>width()){
        setWidth(w);
    }
    if(height()<=0){
        setHeight(1);
    }
}

void Label::setText(const QString &text)
{
    text_binding_ = [text](){ return text; };
    setModified(true);
}

QString Label::text() const
{
    if(text_binding_)
        return text_binding_();
    return "";
}

void Label::bindText(const Label::TextBinding &binding, int width)
{
    text_binding_ = binding;
    if(width>0){
        setWidth(width);
    }
}

bool Label::prevUpdate()
{
    if(modified()){
        adjustSize();
        setModified(false);
    }
    return true;
}

void Label::paintEvent()
{
    writeText(rect(), text(), Color(color()), Color(background()));
}
